//
//  KKImitateWristWatchOutputTool.swift
//  swiftrealm
//
//  Created by KuaiKuai on 2023/3/10.
//
/**
 
 outputer = KKImitateWristWatchOutputTool()
 outputer?.startOutput(output: { uuid,dataUUid,heartRate,steps in
     print("\(uuid),\(dataUUid),\(heartRate),\(steps)")
 })
 
 */

import Foundation
protocol KKImitateWristWatchOutputToolDelegate: AnyObject  {
    
}
typealias ImitateWristWatchOutputBlock = (_ id : Int,
                                       _ heartRate : Int,
                                       _ sportIntensity : Int,
                                       _ burn: Float)  -> Void
typealias stopOutputBlock = () -> Void
public class KKImitateWristWatchOutputTool {
    //时间器
    lazy var mainTimer: DispatchSourceTimer = {
        let _mainTimer = DispatchSource.makeTimerSource(queue: DispatchQueue.global())
        return _mainTimer
    }()
    //倒计时
    static var secondCount = 200
    
    //变量
    static var id = 1100
    static var heartRate = 1
    static var sportIntensity = 0
    static var burn: Float = 20.1
    
    //开始
    func startOutput(output : @escaping ImitateWristWatchOutputBlock, stopOutputBlock: @escaping stopOutputBlock)   {
        mainTimer.schedule(deadline: .now(), repeating: .seconds(1))
        // 设定时间源的触发事件
        mainTimer.setEventHandler(handler: { [weak self] in
            KKImitateWristWatchOutputTool.secondCount-=1
            
            //暂停
            if KKImitateWristWatchOutputTool.secondCount < 1 {
                stopOutputBlock()
                self?.stopOutput()
                return
            }
            
            if KKImitateWristWatchOutputTool.secondCount > 1 {
                DispatchQueue.main.async { [weak self] in
                    
                    guard let self = self else {
                        return
                    }
                    KKImitateWristWatchOutputTool.id+=1
                    KKImitateWristWatchOutputTool.heartRate+=5
                    if KKImitateWristWatchOutputTool.heartRate > 100 {
                        KKImitateWristWatchOutputTool.heartRate = 110
                    }
                    
                    KKImitateWristWatchOutputTool.sportIntensity = self.generateRandomNumber(min: 0, max: 90)
                    KKImitateWristWatchOutputTool.burn += Float(self.generateRandomNumber(min: 1, max: 6))
                    output(KKImitateWristWatchOutputTool.id,KKImitateWristWatchOutputTool.heartRate,KKImitateWristWatchOutputTool.sportIntensity,Float(KKImitateWristWatchOutputTool.burn))
                }
            }
            
        })
         mainTimer.resume()
    }
    //停止
    func stopOutput() {
        mainTimer.cancel()
        print("****** 暂 停 *****")
    }
    deinit {
        print("**** 销 毁 ****")
    }
}
extension KKImitateWristWatchOutputTool {
    func generateRandomNumber(min: Int, max: Int) -> Int {
        return Int(arc4random_uniform(UInt32(max - min + 1))) + min
    }
}
